﻿#region Đào Mạnh Hòa
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace GUI.BanLe
{
    public partial class frmXuLy : Form
    {
        #region Delegate
        public delegate void GetString(Boolean capnhat);
        public GetString MyGetData;
        private Boolean kiemtrasua = false;
        bool kiemtra = false;
        #endregion

        #region khởi tạo biến
        #region biến
        bool checkClose = false;
        Entities.HDBanLe hdbanle;
        Entities.HDBanLe temp;
        Entities.ChiTietHDBanle[] chitiethdbanle;
        Entities.ChiTietHDBanle[] hienthi;
        Entities.ChiTietHDBanle[] templv;
        Entities.DiemThuongKhachHang[] diemthuongkhachhang;
        Entities.TyLeTinh[] tyletinh;
        Entities.ChiTietHDBanle save;
        Entities.Thue[] thue;
        Entities.TienTe[] tiente;
        Entities.KhuyenMaiTangHang[] khuyenmaitanghang;
        Entities.ChiTietKhuyenMaiTangHang[] chitietkhuyenmaitanghang;
        Entities.HangHoa[] hanghoa;
        Entities.ChiTietKhoHang[] chitietkhohang;
        Entities.ChinhSachGiaHangHoa[] chinhsachgiahanghoa;
        Entities.ChiTietChinhSachGiaHangHoa[] chitietchinhsachgiahanghoa;
        Entities.GoiHang[] goihang;
        Entities.ChiTietGoiHang[] chitietgoihang;

        bool checkgoihang = false;
        bool khuyenmai = false;
        string mahanghoa = "";
        int soluong = 1;
        int chietkhau = 0;
        string thuegtgt = "0";
        string dongia = "0";
        double tongtienhang, tongchietkhau, tongthuegtgt, tongtien, thanhtien;
        string hanhDong;
        #endregion
        public frmXuLy()
        {
            InitializeComponent();
            try
            {
                dgvHienThi.DataSource = new Entities.ChiTietHDBanle[0];
                fix();
                mahdbanle = getID();
                thue = Common.StaticVariable.InterfaceObject.SelectThue(new Entities.Thue("1"));
                hanghoa = new TimKiem.frmHangHoa().selectData(makho);
                Entities.ChiTietKhoHang tem = new Entities.ChiTietKhoHang();
                tem.MaKho = makho;
                tem.HanhDong = "ChiTietHangTheoKho";
                chitietkhohang = Common.StaticVariable.InterfaceObject.Select_ChiTietKho(tem);

                hanhDong = Common.Constants.Insert;
            }
            catch
            {
            }
        }

        public frmXuLy(Entities.HDBanLe hdbanle)
        {
            InitializeComponent();
            try
            {

                getID();
                Entities.CaiDatKho kho = Entitystatic.ViewFile();
                makho = kho.MaKho;
                tenkho = kho.TenKho;
                thue = Common.StaticVariable.InterfaceObject.SelectThue(new Entities.Thue("1"));

                date = Entitystatic.date;

                temp = hdbanle;
                this.hdbanle = hdbanle;
                chitiethdbanle = HienThiChiTiet(hdbanle);
                templv = chitiethdbanle;

                dgvHienThi.DataSource = chitiethdbanle;
                fix();
                XuLyDuLieu(hdbanle);
                hanhDong = Common.Constants.Update;
                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
            }
            catch
            {
            }
        }

        void fix()
        {
            for (int i = 0; i < dgvHienThi.ColumnCount; i++)
            {
                dgvHienThi.Columns[i].Visible = false;
            }
            dgvHienThi.ReadOnly = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.SoLuong].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.TenHangHoa].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.DonGia].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.PhanTramChietKhau].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.ThueGTGT].Visible = true;
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.ThanhTien].Visible = true;

            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.SoLuong].HeaderText = "Số Lượng";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.TenHangHoa].HeaderText = "Tên Hàng";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.DonGia].HeaderText = "Giá";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.PhanTramChietKhau].HeaderText = "%CK";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.ThueGTGT].HeaderText = "%GTGT";
            dgvHienThi.Columns[Common.Constants.ChiTietHDBanLe.ThanhTien].HeaderText = "Thành Tiền";

            dgvHienThi.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvHienThi.AllowUserToAddRows = false;
            dgvHienThi.AllowUserToDeleteRows = false;
            dgvHienThi.AllowUserToResizeRows = false;
            dgvHienThi.RowHeadersVisible = false;
        }

        public Entities.ChiTietHDBanle[] HienThi()
        {
            try
            {
                ArrayList array = new ArrayList();
                Entities.ChiTietHDBanle[] temp = Common.StaticVariable.InterfaceObject.SelectChiTietHDBanLe();
                foreach (Entities.ChiTietHDBanle item in temp)
                {
                    array.Add(item);
                }
                Entities.ChiTietHDBanle[] chitiethdbanle = (Entities.ChiTietHDBanle[])array.ToArray(typeof(Entities.ChiTietHDBanle));
                return chitiethdbanle;
            }
            catch
            {
                return new Entities.ChiTietHDBanle[0];
            }

        }

        public Entities.ChiTietHDBanle[] HienThiChiTiet(Entities.HDBanLe hdbanle)
        {
            try
            {
                ArrayList array = new ArrayList();
                Entities.ChiTietHDBanle[] temp = Common.StaticVariable.InterfaceObject.SelectChiTietHDBanLe();
                foreach (Entities.ChiTietHDBanle item in temp)
                {
                    if (item.MaHDBanLe == hdbanle.MaHDBanLe)
                        array.Add(item);
                }
                Entities.ChiTietHDBanle[] chitiethdbanle = (Entities.ChiTietHDBanle[])array.ToArray(typeof(Entities.ChiTietHDBanle));
                return chitiethdbanle;
            }
            catch
            {
                return new Entities.ChiTietHDBanle[0];
            }

        }

        #endregion

        #region Thanh Toán

        void ThanhToan()
        {
            try
            {
                chitiethdbanle = (Entities.ChiTietHDBanle[])dgvHienThi.DataSource;
                // check object
                if (chitiethdbanle == null || chitiethdbanle.Length == 0)
                {
                    MessageBox.Show(Common.MSG.MSG23(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    return;
                }
                else
                {
                    this.ChiTietHoaDonBanLe(chitiethdbanle);
                }

                if (hdbanle == null)
                {
                    hdbanle = XuLyObject(Common.Constants.Insert);
                    if (hdbanle == null)
                    {
                        return;
                    }
                }
                try
                {
                    hdbanle.DanhSach = chitiethdbanle;
                    hdbanle.DanhSachTruKho = DanhSach;
                    hdbanle.ChietKhau = TinhChietKhau();
                    hdbanle.TongTienThanhToan = txtTongTien.Text.ToString();
                    hdbanle.ThueGTGT = TinhThue();
                }
                catch { }
                frmThanhToan xuly = new frmThanhToan(this.hanhDong, hdbanle);
                xuly.ShowDialog();
                if (!frmThanhToan.kiemtra)
                {
                    // check conflic insert
                    if (!CheckConflicInsert(hdbanle))
                    {
                        MessageBox.Show(Common.MSG.MSG5(hdbanle.MaHDBanLe), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        mahdbanle = mahdbanlemoi;
                        hdbanle.MaHDBanLe = mahdbanle;
                        return;
                    }
                    // check insert
                    // check update giá trị còn lại thẻ vip
                    if (hdbanle.MaTheVip.Length != 0)
                    {
                        Entities.TheVip thevip = XuLyObjectTheVip(Common.Constants.Update);
                        hdbanle.TheVip = thevip;
                    }
                    // check update điểm thưởng khách hàng
                    if (txtMaKhachHang.Text.Length != 0 && txtMaKhachHang.Text != "<F4 - Tra cứu>")
                    {
                        Entities.DiemThuongKhachHang diemthuongkhachhang = XuLyDiemThuongKhachHang();
                        hdbanle.DiemThuongKhachHang = diemthuongkhachhang;
                    }
                    hdbanle.PhieuTTCuaKH = ThemPhieuThanhToan(hdbanle);
                    hdbanle.ChiTietPhieuTTCuaKH = ThemChiTietPhieuThanhToan(hdbanle, hdbanle.PhieuTTCuaKH.MaPhieuTTCuaKH);
                    hdbanle.TaiKhoan = UtilitiesVariable.User;
                    
                    if (Common.StaticVariable.InterfaceObject.InsertUpdateHDBanLe(hdbanle) == 0)
                    {
                        MessageBox.Show(Common.MSG.MSG15(hdbanle.MaHDBanLe), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return;
                    }

                    this.Enabled = false;
                    In(hdbanle);
                    this.Enabled = true;
                    kiemtra = true;
                    checkClose = true;
                    hdbanle = null;
                    this.Close();
                }
                frmThanhToan.kiemtra = false;

            }
            catch
            {
                MessageBox.Show(Common.MSG.MSG15(hdbanle.MaHDBanLe), Common.MSG.TieuDe, MessageBoxButtons.OK);
                return;
            }
            finally
            {
                txtMaHangHoa.Focus();
            }
        }

        Entities.ChiTietKhoHang[] CheckListView(Entities.ChiTietHDBanle[] hienthi)
        {
            try
            {
                Entities.ChiTietKhoHang[] ctkh = new Entities.ChiTietKhoHang[hienthi.Length];
                int sotang = 0;
                foreach (Entities.ChiTietHDBanle item in hienthi)
                {
                    int soluongtrongkho = 0;
                    // lấy số lượng trong kho
                    foreach (Entities.ChiTietKhoHang item1 in chitietkhohang)
                    {
                        if (item1.MaHangHoa == item.MaHangHoa)
                        {
                            soluongtrongkho = int.Parse(item1.SoLuong);
                            break;
                        }
                    }
                    ctkh[sotang] = new Entities.ChiTietKhoHang();
                    ctkh[sotang].MaKho = makho;
                    ctkh[sotang].MaHangHoa = item.MaHangHoa;
                    ctkh[sotang].SoLuong = (soluongtrongkho - item.SoLuong).ToString();
                    sotang++;
                }
                return ctkh;
            }
            catch
            {
                return new Entities.ChiTietKhoHang[0];
            }
        }

        Entities.TheVip XuLyObjectTheVip(string hanhDong)
        {
            try
            {
                Entities.TheVip thevip = new Entities.TheVip();
                thevip.HanhDong = hanhDong;
                thevip.MaTheVip = hdbanle.MaTheVip;
                thevip.Deleted = false;
                thevip.GhiChu = string.Empty;
                double giatriconlai = 0;
                if (Convert.ToDouble(hdbanle.TongTienThanhToan) < Convert.ToDouble(hdbanle.GiaTriThe))
                {
                    giatriconlai = Convert.ToDouble(hdbanle.GiaTriThe) - Convert.ToDouble(hdbanle.TongTienThanhToan);
                }
                thevip.GiaTriConLai = giatriconlai.ToString();
                thevip.LoaiThe = "";
                thevip.MaKhachHang = "";
                thevip.TenKhachHang = "";
                thevip.TheVipID = 0;
                return thevip;
            }
            catch
            {
                return null;
            }
        }

        Entities.DiemThuongKhachHang XuLyDiemThuongKhachHang()
        {
            try
            {
                if (tyletinh.Length != 0)
                {
                    double tongthanhtoan = double.Parse(hdbanle.TongTienThanhToan) - double.Parse(hdbanle.GiaTriThe);
                    if (tongthanhtoan >= double.Parse(tyletinh[tyletinh.Length - 1].SoTien))
                    {
                        Entities.DiemThuongKhachHang diemthuongkhachhang = TimDiemThuongKhachHang();
                        if (diemthuongkhachhang == null)
                        {
                            diemthuongkhachhang = new Entities.DiemThuongKhachHang();
                            diemthuongkhachhang.Deleted = false;
                            diemthuongkhachhang.DiemDaDung = "0";
                            diemthuongkhachhang.DiemThuongKhachHangID = 0;
                            diemthuongkhachhang.GhiChu = "";
                            diemthuongkhachhang.HanhDong = Common.Constants.Insert;
                            diemthuongkhachhang.MaDiemThuongKhachHang = new DiemThuongKhachHang.frmXuLy().getID();
                            diemthuongkhachhang.MaKhachHang = hdbanle.MaKhachHang;
                            diemthuongkhachhang.TenKhachHang = hdbanle.TenKhachHang;
                            int diemthuonghd = int.Parse(tongthanhtoan.ToString()) / int.Parse(tyletinh[tyletinh.Length - 1].SoTien);
                            diemthuongkhachhang.TongDiem = diemthuonghd.ToString();
                            diemthuongkhachhang.DiemConLai = diemthuongkhachhang.TongDiem;
                            return diemthuongkhachhang;
                        }
                        else
                        {
                            int diemthuonghd = int.Parse(tongthanhtoan.ToString()) / int.Parse(tyletinh[tyletinh.Length - 1].SoTien);
                            diemthuongkhachhang.TongDiem = (double.Parse(diemthuongkhachhang.TongDiem) + diemthuonghd).ToString();
                            diemthuongkhachhang.HanhDong = Common.Constants.Update;
                            return diemthuongkhachhang;
                        }
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }

        Entities.DiemThuongKhachHang TimDiemThuongKhachHang()
        {
            try
            {
                foreach (Entities.DiemThuongKhachHang item in this.diemthuongkhachhang)
                {
                    if (item.MaKhachHang == hdbanle.MaKhachHang)
                    {
                        return item;
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region Check Conflic Insert
        string mahdbanlemoi;
        public bool CheckConflicInsert(Entities.HDBanLe hdbanle)
        {
            try
            {
                mahdbanlemoi = get_ID(hdbanle.MaHDBanLe);
                if (hdbanle.MaHDBanLe == mahdbanlemoi)
                {
                    return true;
                }
                else
                {
                    mahdbanlemoi = getID();
                    return false;
                }
            }
            catch
            {
                mahdbanlemoi = getID();
                return false;
            }
        }
        #endregion

        #region Thẻ Vip
        void TheVip()
        {
            {
                try
                {
                    chitiethdbanle = (Entities.ChiTietHDBanle[])dgvHienThi.DataSource;
                    // check object
                    if (chitiethdbanle == null || chitiethdbanle.Length == 0)
                    {
                        MessageBox.Show(Common.MSG.MSG23(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return;
                    }
                    if (hdbanle == null)
                    {
                        hdbanle = XuLyObject(Common.Constants.Insert);
                        if (hdbanle == null)
                        {
                            return;
                        }
                    }

                    hdbanle.ChietKhau = TinhChietKhau();
                    hdbanle.TongTienThanhToan = txtTongTien.Text.ToString();
                    hdbanle.ThueGTGT = TinhThue();

                    frmTheVip xuly = new frmTheVip(hdbanle, btnThanhToan.Enabled);
                    xuly.ShowDialog();
                    hdbanle = frmTheVip.hdbanle;
                    frmTheVip.hdbanle = null;
                    if (!frmTheVip.kiemtra)
                    {
                        ThanhToan();
                    }
                    frmTheVip.kiemtra = false;
                }
                catch
                {
                }
                finally
                {
                    txtMaHangHoa.Focus();
                }
            }
        }
        #endregion

        #region Thoát
        void Thoat()
        {
            this.Close();
        }
        #endregion

        #region In
        void In(Entities.HDBanLe hdbanbuon)
        {
            Entities.ChiTietHDBanle[] cthdbb = (Entities.ChiTietHDBanle[])dgvHienThi.DataSource;
            int sotang = 0;
            tongthuegtgt = 0;
            Entities.BCHDBanLe[] bc = new Entities.BCHDBanLe[cthdbb.Length];
            foreach (Entities.ChiTietHDBanle item in cthdbb)
            {
                bc[sotang] = new Entities.BCHDBanLe();
                bc[sotang].SoLuong = int.Parse(string.Format("{0:0}", double.Parse(item.SoLuong.ToString())));
                bc[sotang].GiaBanle = double.Parse(item.DonGia);
                bc[sotang].MaHDBanHang = item.MaHDBanLe;
                bc[sotang].TenHangHoa = item.TenHangHoa;
                double thue = double.Parse(item.ThueGTGT);
                double dongia = double.Parse(item.DonGia);
                double chietkhau = double.Parse(item.PhanTramChietKhau);
                double dongiamoi = dongia - ((dongia * chietkhau) / 100);
                int sl = int.Parse(string.Format("{0:0}", double.Parse(item.SoLuong.ToString())));
                tongthuegtgt += sl * ((dongiamoi * thue)) / 100;
                sotang++;
            }

            hdbanle.ThueGTGT = tongthuegtgt.ToString();
            BaoCao.frmBaoCaorpt frm = new BaoCao.frmBaoCaorpt(bc, hdbanbuon);
            if (frm.kiemtra)
            {
                frm.ShowDialog();
            }
        }
        #endregion

        #region get id
        DateTime date;
        private void Binding()
        {
            try
            {
                date = Entitystatic.date;
                Entities.CaiDatKho kho = Entitystatic.ViewFile();
                makho = kho.MaKho;
                tenkho = kho.TenKho;
            }
            catch { }
        }
        public string getID()
        {
            string str = string.Empty;
            try
            {
                Binding();
                str = "HDBL/" + Common.Utilities.GetDateID(date.ToString("dd/MM/yyyy")) + "_" + Common.Utilities.RandomID();
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                str = "HDBL/" + Common.Utilities.GetDateID(date.ToString("dd/MM/yyyy")) + "_" + Common.Utilities.RandomID();
            }
            return str;
        }
        public string get_ID(string mahoadon)
        {
            string str = string.Empty;
            try
            {
                Binding();
                Entities.GetID layid = new Entities.GetID();
                layid.MaHoaDon = mahoadon;
                layid.MaKho = makho;
                layid.Ngay = date.ToString("MM/dd/yyyy");
                Entities.GetID lay = Common.StaticVariable.InterfaceObject.sp_getID_BanLe(layid);
                if (lay.ColumnName == null)
                {
                    str = mahoadon;
                }
                else
                {
                    str = "HDBL/" + Common.Utilities.GetDateID(date.ToString("dd/MM/yyyy")) + "_" + Common.Utilities.RandomID();
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                str = "HDBL/" + Common.Utilities.GetDateID(date.ToString("dd/MM/yyyy")) + "_" + Common.Utilities.RandomID();
            }
            return str;
        }
        #endregion

        #region validate
        public bool Validate()
        {
            return true;
        }

        public bool ValidateDetails()
        {
            try
            {
                if (txtMaHangHoa.Text.Length == 0 || txtMaHangHoa.Text == "<F4 - Tra cứu>")
                {
                    MessageBox.Show(Common.MSG.MSG13(lbMaHangHoa.Text), Common.MSG.TieuDe, MessageBoxButtons.OK);
                    txtMaHangHoa.Focus();
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        Entities.HDBanLe hdtemp;
        public string mahdbanle = "";
        public string manhanvien = "";
        public string tennhanvien = "";
        public string makho = "";
        public string tenkho = "";
        public string mathevip = "";
        public string giatrithe = "";
        public void XuLyDuLieu(Entities.HDBanLe hdbanle)
        {
            try
            {
                mahdbanle = hdbanle.MaHDBanLe;
                manhanvien = hdbanle.MaNhanVien;
                tennhanvien = hdbanle.TenNhanVien;
                makho = hdbanle.MaKho;
                tenkho = hdbanle.TenKho;
                txtMaKhachHang.Text = hdbanle.MaKhachHang;
                txtTenKhachHang.Text = hdbanle.TenKhachHang;
                date = hdbanle.NgayLap;
                mathevip = hdbanle.MaTheVip;
                giatrithe = hdbanle.GiaTriThe;
            }
            catch
            {
            }
        }

        public Entities.HDBanLe XuLyObject(string hanhDong)
        {
            try
            {
                if (Validate())
                {
                    hdtemp = new Entities.HDBanLe();
                    hdtemp.HanhDong = hanhDong;
                    hdtemp.MaHDBanLe = mahdbanle;
                    string makhachhang = string.Empty;
                    if (txtMaKhachHang.Text != "<F4 - Tra cứu>")
                        makhachhang = txtMaKhachHang.Text;
                    hdtemp.MaKhachHang = makhachhang;
                    hdtemp.TenKhachHang = txtTenKhachHang.Text;
                    hdtemp.MaNhanVien = "";
                    hdtemp.TenNhanVien = "";
                    hdtemp.MaKho = makho;
                    hdtemp.TenKho = tenkho;
                    hdtemp.NgayLap = date.Date;
                    hdtemp.MaTheVip = "";
                    hdtemp.GiaTriThe = "0";
                    hdtemp.Deleted = false;
                    hdtemp.TaiKhoan = UtilitiesVariable.User;
                    return hdtemp;
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region Xử lý list view

        string LayThue(string mathue)
        {
            try
            {
                foreach (Entities.Thue item in thue)
                {
                    if (item.MaThue == mathue)
                    {
                        return item.GiaTriThue;
                    }
                }
                return "0";
            }
            catch
            {
                return "0";
            }
        }

        string TinhThue()
        {
            try
            {
                tongthuegtgt = 0;
                foreach (Entities.ChiTietHDBanle item in templv)
                {
                    double thue = double.Parse(item.ThueGTGT);
                    double dongia = double.Parse(item.DonGia);
                    double chietkhau = double.Parse(item.PhanTramChietKhau);
                    double dongiamoi = dongia - ((dongia * chietkhau) / 100);
                    tongthuegtgt += (dongiamoi * thue) / 100;
                }
                return tongthuegtgt.ToString();
            }
            catch
            {
                return "0";
            }
        }
        string TinhChietKhau()
        {
            try
            {
                tongchietkhau = 0;
                foreach (Entities.ChiTietHDBanle item in templv)
                {
                    double dongia = double.Parse(item.DonGia);
                    double sl = item.SoLuong;
                    double chietkhau = double.Parse(item.PhanTramChietKhau);
                    tongchietkhau += ((dongia * sl) * chietkhau) / 100;
                }
                return tongchietkhau.ToString();
            }
            catch
            {
                return "0";
            }
        }
        string TongTienHang()
        {
            try
            {
                tongtienhang = 0;
                foreach (Entities.ChiTietHDBanle item in templv)
                {
                    double dongia = double.Parse(item.DonGia);
                    double chietkhau = double.Parse(item.PhanTramChietKhau);
                    tongtienhang += dongia - ((dongia * chietkhau) / 100);

                }
                return tongtienhang.ToString();
            }
            catch
            {
                return "0";
            }
        }
        string TongTien()
        {
            try
            {
                tongtien = 0;
                foreach (Entities.ChiTietHDBanle item in templv)
                {
                    tongtien += double.Parse(item.ThanhTien);
                }
                return tongtien.ToString();
            }
            catch
            {
                return "0";
            }
        }
        #endregion

        #region New Row
        void NewRow()
        {
            if (hanhDong != Common.Constants.Insert) return;
            {
                try
                {
                    string dongiasosanh = dongia;
                    int sohangtrongbang;
                    hienthi = (Entities.ChiTietHDBanle[])dgvHienThi.DataSource;
                    soluong = int.Parse(txtSoLuong.Text);
                    // list view = null
                    if (hienthi == null)
                    {
                        templv = new Entities.ChiTietHDBanle[1];
                        double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                        double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                        thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluong;
                        templv[0] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, txtMaHangHoa.Text, txtTenHangHoa.Text,
                            soluong, dongia, chietkhau.ToString(), thuegtgt, thanhtien.ToString(), "", false, khuyenmai);
                        dgvHienThi.DataSource = templv;
                        return;
                    }

                    sohangtrongbang = hienthi.Length;
                    // số lượng bảng ghi khác 0
                    if (sohangtrongbang > 0)
                    {
                        for (int j = 0; j < sohangtrongbang; j++)
                        {
                            // nếu tìm được mã đã có trong list view
                            if (mahanghoa.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && dongiasosanh == hienthi[j].DonGia)
                            {
                                templv = new Entities.ChiTietHDBanle[sohangtrongbang];
                                break;
                            }
                            // nếu không tìm được
                            else
                                templv = new Entities.ChiTietHDBanle[sohangtrongbang + 1];
                        }
                    }
                    // số lượng bảng ghi = 0
                    else
                        templv = new Entities.ChiTietHDBanle[sohangtrongbang + 1];
                    // nếu số lượng bảng ghi khác 0
                    if (templv.Length != 0)
                    {
                        try
                        {
                            // số lượng bảng ghi = số lượng row list view
                            if (templv.Length == hienthi.Length)
                            {
                                SoLuongBangSoLuong(templv, hienthi);
                            }
                            // số lượng bảng ghi không = số lượng row list view
                            else
                            {
                                SoLuongKhacSoLuong(templv, hienthi);
                            }
                        }
                        catch
                        {
                            double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                            double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                            thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluong;

                            templv[templv.Length - 1] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, txtMaHangHoa.Text, txtTenHangHoa.Text,
                                                soluong, dongia, chietkhau.ToString(), thuegtgt, thanhtien.ToString(), "", false, khuyenmai);
                        }
                        dgvHienThi.DataSource = templv;
                    }
                }
                catch
                {
                    return;
                }
                finally
                {
                    soluong = 1;
                    mahanghoa = "";
                    khuyenmai = false;
                    txtMaHangHoa.Text = "";
                    txtTenHangHoa.Text = "";
                    txtMaHangHoa.Focus();
                    dongia = "0";
                    txtDonGia.Text = dongia;
                    txtSoLuong.Text = soluong.ToString();
                    chietkhau = 0;
                    thuegtgt = "0";
                    thanhtien = 0;
                    dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);

                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                }
            }
        }

        void SoLuongBangSoLuong(Entities.ChiTietHDBanle[] templv, Entities.ChiTietHDBanle[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {
                string dongiasosanh = dongia;
                // nếu mã = mã trong list view
                if (mahanghoa.ToUpper() == hienthi[j].MaHangHoa.ToUpper() && dongiasosanh == hienthi[j].DonGia)
                {
                    int soluongcu = hienthi[j].SoLuong;
                    int soluonghientai = soluongcu + soluong;
                    double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                    thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * soluonghientai);

                    templv[j] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, txtMaHangHoa.Text.ToUpper(), txtTenHangHoa.Text,
                            soluonghientai, dongia, chietkhau.ToString(), thuegtgt, thanhtien.ToString(), "", false, khuyenmai);

                }
                // nếu mã không = mã trong list view
                else
                    templv[j] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);

            }
        }

        void SoLuongKhacSoLuong(Entities.ChiTietHDBanle[] templv, Entities.ChiTietHDBanle[] hienthi)
        {
            for (int j = 0; j < templv.Length; j++)
            {
                // lấy lại số bảng ghi trên list view
                if (j < templv.Length - 1)
                    templv[j] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);
                // bảng ghi cuối cùng là mới insert vào
                else
                {
                    double dongiadachietkhau = (double.Parse(dongia)) - (((double.Parse(dongia)) * chietkhau) / 100);
                    double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                    thanhtien = ((dongiadachietkhau + thuegtgtdachietkhau) * soluong);
                    templv[templv.Length - 1] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, txtMaHangHoa.Text, txtTenHangHoa.Text,
                            soluong, dongia, chietkhau.ToString(), thuegtgt, thanhtien.ToString(), "", false, khuyenmai);
                }

            }
        }


        void AddRowMang()
        {
            try
            {
                bool kt = false;
                foreach (Entities.HangHoa item in manghanghoa)
                {
                    if (!kt)
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = LayThue(item.MaThue);
                        dongia = item.GiaBanLe;
                        txtDonGia.Text = dongia;
                        soluong = item.SoLuong;
                        khuyenmai = true;
                        kt = true;
                    }
                    else
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = "0";
                        dongia = "0";
                        txtDonGia.Text = dongia;
                        chietkhau = 0;
                        soluong = item.SoLuong;
                    }
                    NewRow();
                }
            }
            catch
            {
            }
        }

        #endregion

        #region Sửa Hàng Hóa
        void SuaHangHoa()
        {
            if (hanhDong != Common.Constants.Insert) return;
            {
                try
                {
                    // obj = null
                    if (save == null)
                    {
                        return;
                    }
                    if (save.DonGia == "0")
                    {
                        MessageBox.Show(Common.MSG.MSG25(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return;
                    }
                    frmNhapSoLuong frm = new frmNhapSoLuong();
                    frm.ShowDialog();
                    if (frmNhapSoLuong.soluong == 0)
                    {
                        return;
                    }
                    soluong = frmNhapSoLuong.soluong;
                    frmNhapSoLuong.soluong = 0;
                    hienthi = (Entities.ChiTietHDBanle[])dgvHienThi.DataSource;
                    // list view = null
                    if (hienthi == null)
                    {
                        return;
                    }
                    if (save.KhuyenMai)
                    {
                        Entities.ChiTietHDBanle temp = save;
                        SuaHangHoaKhuyenMai(temp, soluong);
                    }
                    else
                    {
                        SuaHangHoaKhongKhuyenMai();
                    }
                }
                catch
                {
                }
                finally
                {
                    dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);
                    fix();
                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                    save = null;
                    txtMaHangHoa.Focus();
                }
            }
        }

        void SuaHangHoaKhongKhuyenMai()
        {
            try
            {
                templv = new Entities.ChiTietHDBanle[hienthi.Length];
                int sotang = 0;
                for (int j = 0; j < hienthi.Length; j++)
                {
                    if (hienthi[j].MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper())
                    {
                        templv[sotang] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);
                        sotang++;
                    }
                    else
                    {
                        dongia = hienthi[j].DonGia;
                        chietkhau = int.Parse(hienthi[j].PhanTramChietKhau);
                        thuegtgt = hienthi[j].ThueGTGT;
                        double dongiadachietkhau = double.Parse(dongia) - ((double.Parse(dongia) * chietkhau) / 100);
                        double thuegtgtdachietkhau = (dongiadachietkhau * double.Parse(thuegtgt)) / 100;
                        thanhtien = (dongiadachietkhau + thuegtgtdachietkhau) * soluong;
                        templv[sotang] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                                 soluong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, thanhtien.ToString(), "", false, hienthi[j].KhuyenMai);
                        sotang++;
                    }
                }
                dgvHienThi.DataSource = templv;
                fix();
                save = null;
            }
            catch
            {
            }
            finally
            {
                soluong = 1;
                txtSoLuong.Text = soluong.ToString();
                khuyenmai = false;
                dongia = "0";
                txtDonGia.Text = dongia;
                chietkhau = 0;
                thuegtgt = "0";
                thanhtien = 0;
            }
        }

        void SuaHangHoaKhuyenMai(Entities.ChiTietHDBanle save, int soluog)
        {
            try
            {
                dgvHienThi.DataSource = null;
                ArrayList list = new ArrayList();
                foreach (Entities.ChiTietHDBanle item in hienthi)
                {
                    if (item.KhuyenMai)
                    {

                        if (item.MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper())
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            soluong = item.SoLuong;
                            manghanghoa = CheckSuaHangHoaKhuyenMai();
                            if (manghanghoa.Length != 0)
                            {
                                SuaHangHoaTheoMang();
                            }
                        }
                        else
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            soluong = soluog;
                            manghanghoa = CheckSuaHangHoaKhuyenMai();
                            if (manghanghoa.Length != 0)
                            {
                                SuaHangHoaTheoMang();
                            }

                        }
                    }
                    else
                    {
                        if (item.DonGia != "0")
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                            txtTenHangHoa.Text = item.TenHangHoa;
                            thuegtgt = LayThue(item.ThueGTGT);
                            dongia = item.DonGia;
                            txtDonGia.Text = dongia;
                            soluong = item.SoLuong;
                            khuyenmai = item.KhuyenMai;
                            NewRow();
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                manghanghoa = null;
                txtMaHangHoa.Focus();
            }
        }

        Entities.HangHoa[] CheckSuaHangHoaKhuyenMai()
        {
            try
            {
                ArrayList array = new ArrayList();
                bool kt = false;
                foreach (Entities.ChiTietKhuyenMaiTangHang item in ctkmth)
                {

                    if (item.MaHangKhuyenMai.ToUpper() == mahanghoa.ToUpper())
                    {
                        khuyenmai = true;
                        if (item.SoLuongKhuyenMai <= soluong)
                        {
                            tyle = soluong / item.SoLuongKhuyenMai;
                            if (item.MaHangDuocKhuyenmai == item.MaHangKhuyenMai)
                            {
                                Entities.HangHoa hh;
                                // hàng khuyến mại
                                int soluongdu = soluong - (item.SoLuongKhuyenMai * tyle);
                                hh = LayHangHoa(item.MaHangKhuyenMai.ToUpper(), (item.SoLuongKhuyenMai * tyle) + soluongdu, true);
                                mahanghoa = hh.MaHangHoa.ToUpper();
                                txtMaHangHoa.Text = hh.MaHangHoa.ToUpper();
                                txtTenHangHoa.Text = hh.TenHangHoa;
                                thuegtgt = LayThue(hh.MaThue);
                                dongia = hh.GiaBanLe;
                                txtDonGia.Text = dongia;
                                soluong = hh.SoLuong;
                                khuyenmai = hh.KhuyenMai;
                                NewRow();

                                // hàng được KM
                                hh = LayHangHoa(item.MaHangDuocKhuyenmai.ToUpper(), item.SoLuongDuocKhuyenMai * tyle, false);
                                mahanghoa = hh.MaHangHoa.ToUpper();
                                txtMaHangHoa.Text = hh.MaHangHoa.ToUpper();
                                txtTenHangHoa.Text = hh.TenHangHoa;
                                thuegtgt = "0";
                                dongia = "0";
                                txtDonGia.Text = dongia;
                                chietkhau = 0;
                                soluong = hh.SoLuong;
                                khuyenmai = hh.KhuyenMai;
                                NewRow();
                            }
                            else
                            {
                                if (!kt)
                                {
                                    int soluongdu = soluong - (item.SoLuongKhuyenMai * tyle);
                                    array.Add(LayHangHoa(item.MaHangKhuyenMai, (item.SoLuongKhuyenMai * tyle) + soluongdu, true));
                                    array.Add(LayHangHoa(item.MaHangDuocKhuyenmai, item.SoLuongDuocKhuyenMai * tyle, false));
                                    kt = true;
                                }
                                else
                                    array.Add(LayHangHoa(item.MaHangDuocKhuyenmai, item.SoLuongDuocKhuyenMai * tyle, false));
                            }
                        }
                        else
                        {
                            Entities.HangHoa hh;
                            // hàng khuyến mại
                            hh = LayHangHoa(item.MaHangKhuyenMai.ToUpper(), soluong, true);
                            mahanghoa = hh.MaHangHoa.ToUpper();
                            txtMaHangHoa.Text = hh.MaHangHoa.ToUpper();
                            txtTenHangHoa.Text = hh.TenHangHoa;
                            thuegtgt = LayThue(hh.MaThue);
                            dongia = hh.GiaBanLe;
                            txtDonGia.Text = dongia;
                            soluong = hh.SoLuong;
                            khuyenmai = hh.KhuyenMai;
                            NewRow();
                        }
                    }

                }
                manghanghoa = (Entities.HangHoa[])array.ToArray(typeof(Entities.HangHoa));
                return manghanghoa;
            }
            catch
            {
                return new Entities.HangHoa[0];
            }
        }

        void SuaHangHoaTheoMang()
        {
            try
            {
                foreach (Entities.HangHoa item in manghanghoa)
                {

                    if (item.KhuyenMai)
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = LayThue(item.MaThue);
                        dongia = item.GiaBanLe;
                        txtDonGia.Text = dongia;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    else
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = "0";
                        dongia = "0";
                        txtDonGia.Text = dongia;
                        chietkhau = 0;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    NewRow();
                }
            }
            catch
            {
            }
            finally
            {
                txtMaHangHoa.Focus();
            }
        }
        #endregion

        #region Xóa Hàng Hóa
        void XoaHangHoa()
        {
            if (hanhDong != Common.Constants.Insert) return;
            {
                try
                {
                    hienthi = (Entities.ChiTietHDBanle[])dgvHienThi.DataSource;
                    // list view = null
                    if (hienthi == null)
                    {
                        return;
                    }
                    // obj = null
                    if (save == null)
                    {
                        return;
                    }
                    if (save.DonGia == "0")
                    {
                        MessageBox.Show(Common.MSG.MSG26(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return;
                    }
                    if (save.KhuyenMai)
                    {
                        Entities.ChiTietHDBanle temp = save;
                        XoaHangHoaKhuyenMai(temp);
                    }
                    else
                    {
                        XoaHangHoaKhongKhuyenMai();
                    }
                }
                catch
                {
                }
                finally
                {
                    dgvHienThi.DataSource = XuLyChinhSachGiaHangHoa(templv);
                    fix();
                    txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                    save = null;
                    txtMaHangHoa.Focus();
                }
            }
        }

        void XoaHangHoaKhuyenMai(Entities.ChiTietHDBanle save)
        {
            hienthi = (Entities.ChiTietHDBanle[])dgvHienThi.DataSource;
            try
            {
                bool kt = false;
                dgvHienThi.DataSource = null;
                ArrayList list = new ArrayList();
                foreach (Entities.ChiTietHDBanle item in hienthi)
                {
                    if (item.MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper())
                    {
                        if (item.KhuyenMai)
                        {
                            mahanghoa = item.MaHangHoa.ToUpper();
                            soluong = item.SoLuong;
                            manghanghoa = CheckSuaHangHoaKhuyenMai();
                            XoaHangHoaTheoMang();
                            kt = true;
                        }
                        if (item.KhuyenMai == false)
                        {
                            if (item.DonGia != "0")
                            {
                                mahanghoa = item.MaHangHoa.ToUpper();
                                txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                                txtTenHangHoa.Text = item.TenHangHoa;
                                thuegtgt = LayThue(item.ThueGTGT);
                                dongia = item.DonGia;
                                txtDonGia.Text = dongia;
                                soluong = item.SoLuong;
                                khuyenmai = item.KhuyenMai;
                                NewRow();
                                kt = true;
                            }
                        }
                    }
                }
                if (!kt)
                {
                    templv = new Entities.ChiTietHDBanle[0];
                    dgvHienThi.DataSource = templv;
                    fix();
                }
            }
            catch
            {
            }
            finally
            {
                manghanghoa = null;
                txtMaHangHoa.Focus();
            }
        }

        void XoaHangHoaTheoMang()
        {
            try
            {
                foreach (Entities.HangHoa item in manghanghoa)
                {

                    if (item.KhuyenMai)
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = LayThue(item.MaThue);
                        dongia = item.GiaBanLe;
                        txtDonGia.Text = dongia;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    else
                    {
                        mahanghoa = item.MaHangHoa.ToUpper();
                        txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = item.TenHangHoa;
                        thuegtgt = "0";
                        dongia = "0";
                        txtDonGia.Text = dongia;
                        chietkhau = 0;
                        soluong = item.SoLuong;
                        khuyenmai = item.KhuyenMai;
                    }
                    NewRow();
                }
            }
            catch
            {
            }
            finally
            {
                txtMaHangHoa.Focus();

            }
        }

        void XoaHangHoaKhongKhuyenMai()
        {
            try
            {
                templv = new Entities.ChiTietHDBanle[hienthi.Length - 1];
                int sotang = 0;
                for (int j = 0; j < hienthi.Length; j++)
                {
                    if (hienthi[j].MaHangHoa.ToUpper() != save.MaHangHoa.ToUpper() || hienthi[j].DonGia != save.DonGia)
                    {
                        templv[sotang] = new Entities.ChiTietHDBanle(Common.Constants.Insert, mahdbanle, hienthi[j].MaHangHoa.ToUpper(), hienthi[j].TenHangHoa,
                                 hienthi[j].SoLuong, hienthi[j].DonGia, hienthi[j].PhanTramChietKhau, hienthi[j].ThueGTGT, hienthi[j].ThanhTien, "", false, hienthi[j].KhuyenMai);
                        sotang++;
                    }
                }
                dgvHienThi.DataSource = templv;
                fix();
                save = null;
            }
            catch
            {
            }
            finally
            {
                txtTongTien.Text = Common.Utilities.FormatMoney(TongTien());
                txtMaHangHoa.Focus();
            }
        }
        #endregion

        #region Thêm Hàng Hóa
        void ThemHangHoa()
        {
            if (hanhDong != Common.Constants.Insert) return;
            {
                try
                {
                    if (makho.Length == 0 || makho == "NULL")
                    {
                        MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return;
                    }
                    Entities.KhoHang kh = new Entities.KhoHang();
                    kh.MaKho = makho;
                    TimKiem.frmHangHoa timkiem = new TimKiem.frmHangHoa(kh);
                    timkiem.ShowDialog();
                    if (TimKiem.frmHangHoa.selectedItem != null)
                    {
                        txtMaHangHoa.Text = TimKiem.frmHangHoa.selectedItem.MaHangHoa.ToUpper();
                        txtTenHangHoa.Text = TimKiem.frmHangHoa.selectedItem.TenHangHoa;
                        thuegtgt = LayThue(TimKiem.frmHangHoa.selectedItem.MaThue);
                        dongia = TimKiem.frmHangHoa.selectedItem.GiaBanLe;
                        txtDonGia.Text = dongia;
                        TimKiem.frmHangHoa.selectedItem = null;
                    }
                }
                catch
                {
                }
                finally
                {
                    txtSoLuong.Focus();

                }
            }
        }
        #endregion

        #region Thêm khách hàng
        void ThemKhachHang()
        {
            if (hanhDong != Common.Constants.Insert) return;

            try
            {
                TimKiem.frmKhachHang frm = new TimKiem.frmKhachHang();
                frm.ShowDialog();
                if (TimKiem.frmKhachHang.khachhang != null)
                {
                    txtMaKhachHang.Text = TimKiem.frmKhachHang.khachhang.MaKhachHang;
                    txtTenKhachHang.Text = TimKiem.frmKhachHang.khachhang.Ten;
                    TimKiem.frmKhachHang.khachhang = null;
                    txtMaHangHoa.Focus();
                }
            }
            catch
            {
            }
        }
        #endregion

        #region Xử lý

        private Entities.ChiTietHDBanle[] DanhSach;
        private Boolean KiemTraMaGoiHang(string mahanghoa)
        {
            Boolean kt = false;
            try
            {
                for (int k = 0; k < chitietgoihang.Length; k++)
                {
                    if (chitietgoihang[k].MaGoiHang.ToUpper() == mahanghoa.ToUpper())
                    {
                        kt = true;
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                kt = false;
            }
            return kt;
        }
        private string LaySoLuong(string magoi, string mahanghoa)
        {
            string soluong = "0";
            try
            {
                for (int k = 0; k < chitietgoihang.Length; k++)
                {
                    if (chitietgoihang[k].MaGoiHang.ToUpper() == magoi.ToUpper() && chitietgoihang[k].MaHangHoa.ToString().ToUpper() == mahanghoa.ToUpper())
                    {
                        soluong = Common.Utilities.RemoveChar(chitietgoihang[k].SoLuong.ToString());
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            catch (Exception ex)
            { string s = ex.Message; soluong = "0"; }
            return soluong;
        }
        private void getChiTiet(Entities.ChiTietHDBanle chitiet, string mahanghoa)
        {
            try
            {
                for (int y = 0; y < hanghoa.Length; y++)
                {
                    if (hanghoa[y].MaHangHoa.ToUpper() == mahanghoa.ToUpper())
                    {
                        Entities.ChiTietHDBanle row = new Entities.ChiTietHDBanle();
                        row.HanhDong = Common.Constants.Insert;
                        row.MaKho = this.makho;
                        row.SoLuongConLai = Common.Utilities.RemoveChar(chitiet.SoLuong.ToString());
                        row.MaHDBanLe = mahdbanle;
                        row.SoLuong = chitiet.SoLuong * int.Parse(this.LaySoLuong(chitiet.MaHangHoa, hanghoa[y].MaHangHoa));
                        row.MaHangHoa = mahanghoa;
                        row.TenHangHoa = hanghoa[y].TenHangHoa;
                        row.DonGia = Common.Utilities.RemoveChar(hanghoa[y].GiaBanLe);
                        row.PhanTramChietKhau = "0";
                        row.ThueGTGT = "0";
                        row.ThanhTien = "0";
                        row.GhiChu = "";
                        row.Deleted = false;
                        list.Add(row);
                        break;
                    }
                }

            }
            catch (Exception ex)
            { string s = ex.Message; }
        }

        private void Add(Entities.ChiTietHDBanle chitiet, string magoi)
        {
            try
            {
                for (int k = 0; k < chitietgoihang.Length; k++)
                {
                    if (chitietgoihang[k].MaGoiHang.ToUpper() == magoi.ToUpper())
                    {
                        this.getChiTiet(chitiet, chitietgoihang[k].MaHangHoa);
                    }
                    else
                    { continue; }
                }
            }
            catch (Exception ex)
            { string s = ex.Message; }
        }

        private ArrayList list;
        private void ChiTietHoaDonBanLe(Entities.ChiTietHDBanle[] giatri)
        {
            try
            {
                list = new ArrayList();
                for (int x = 0; x < giatri.Length; x++)
                {
                    giatri[x].MaKho = this.makho;
                    giatri[x].SoLuongConLai = Common.Utilities.RemoveChar(giatri[x].SoLuong.ToString());
                    if (this.KiemTraMaGoiHang(giatri[x].MaHangHoa) == true)
                    {
                        this.Add(giatri[x], giatri[x].MaHangHoa);
                    }
                    else
                    {
                        list.Add(giatri[x]);
                    }
                }
                int n = list.Count;
                if (n == 0) { list = null; }
                DanhSach = new Entities.ChiTietHDBanle[n];
                for (int i = 0; i < n; i++)
                {
                    DanhSach[i] = (Entities.ChiTietHDBanle)list[i];
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
                DanhSach = null;
            }
        }
        private Entities.PhieuTTCuaKH ThemPhieuThanhToan(Entities.HDBanLe hoadon)
        {
            try
            {
                string MaPhieuThanhToan = new PhieuTTCuaKH.frmXuLy("").getID();
                Entities.PhieuTTCuaKH tt = new Entities.PhieuTTCuaKH();
                tt.HanhDong = Common.Constants.GiaTriCacForm.Insert;
                tt.MaPhieuTTCuaKH = MaPhieuThanhToan;
                tt.MaKho = makho;
                tt.NgayLap = hoadon.NgayLap;
                tt.MaKhachHang = hoadon.MaKhachHang;
                tt.TenKhachHang = hoadon.TenKhachHang;
                tt.TongThanhToan = hoadon.TongTienThanhToan;
                tt.NoHienThoi = "0";
                tt.NguoiNop = hoadon.TenKhachHang;
                tt.MaNhanVien = hoadon.MaNhanVien;
                tt.LoaiPhieu = false;
                tt.GhiChu = hoadon.MaHDBanLe;
                tt.Deleted = false;
                return tt;
            }
            catch (Exception ex)
            {
                return new Entities.PhieuTTCuaKH();
            }
        }

        private Entities.ChiTietPhieuTTCuaKH[] ThemChiTietPhieuThanhToan(Entities.HDBanLe hoadon, string maphieuthanhtoan)
        {
            try
            {
                Entities.ChiTietPhieuTTCuaKH[] tt = new Entities.ChiTietPhieuTTCuaKH[1];
                Entities.ChiTietPhieuTTCuaKH row = new Entities.ChiTietPhieuTTCuaKH();
                row.HanhDong = Common.Constants.GiaTriCacForm.Insert;
                row.MaPhieuTTCuaKH = maphieuthanhtoan;
                row.MaHDBanHang = hoadon.MaHDBanLe;
                row.TongTienThanhToan = hoadon.TongTienThanhToan;
                row.SoNo = "0";
                row.ThanhToan = hoadon.TongTienThanhToan;
                row.GhiChu = hoadon.MaHDBanLe;
                row.Deleted = false;
                tt[0] = row;
                return tt;
            }
            catch
            {
                return new Entities.ChiTietPhieuTTCuaKH[0];
            }
        }
        #endregion

        #region Event
        private void frmXuLy_Load(object sender, EventArgs e)
        {
            lblTenNhanVien.Text = UtilitiesVariable.User.TenDangNhap; 
            this.FormClosing += new FormClosingEventHandler(frmXuLy_FormClosing);
            btnThanhToan.Click += new EventHandler(btnThanhToan_Click);
            btnThemGV.Click += new EventHandler(btnThemGV_Click);
            btnTheVip.Click += new EventHandler(btnTheVip_Click);
            btnThoat.Click += new EventHandler(btnThoat_Click);
            btnTimKH.Click += new EventHandler(btnTimKH_Click);
            dgvHienThi.CellClick += new DataGridViewCellEventHandler(dgvHienThi_CellClick);
            dgvHienThi.CellDoubleClick += new DataGridViewCellEventHandler(dgvHienThi_CellDoubleClick);
            dgvHienThi.KeyDown += new KeyEventHandler(dgvHienThi_KeyDown);
            txtMaHangHoa.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtSoLuong.KeyDown += new KeyEventHandler(txt_KeyDown);
            txtMaKhachHang.KeyDown += new KeyEventHandler(txt_KeyDown);
        }

        void dgvHienThi_KeyDown(object sender, KeyEventArgs e)
        {
            if (hanhDong != Common.Constants.Insert)
                return;
            if (i < 0)
                return;
            if (dgvHienThi.RowCount == 0)
                return;
            save = ((Entities.ChiTietHDBanle[])dgvHienThi.DataSource)[i];

            switch (e.KeyData)
            {
                case Keys.Enter:
                    {
                        SuaHangHoa();
                        break;
                    }
                case Keys.Delete:
                    {
                        XoaHangHoa();
                        break;
                    }
            }
        }

        void txt_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyData)
                {
                    case Keys.F4:
                        {
                            TextBox tx = (TextBox)sender;
                            switch (tx.Name)
                            {
                                case "txtMaHangHoa":
                                    {
                                        ThemHangHoa();
                                        break;
                                    }
                                case "txtMaKhachHang":
                                    {
                                        ThemKhachHang();
                                        break;
                                    }
                            }
                            break;
                        }
                    case Keys.Enter:
                        {
                            TextBox tx = (TextBox)sender;
                            switch (tx.Name)
                            {
                                case "txtSoLuong":
                                    {
                                        XuLy_Enter();
                                        break;
                                    }
                                case "txtMaHangHoa":
                                    {
                                        if (XuLy_EnterMaHangHoa())
                                        {
                                            txtSoLuong.Focus();
                                            txtSoLuong.SelectAll();
                                        }
                                        break;
                                    }
                                case "txtMaKhachHang":
                                    {
                                        txtMaHangHoa.Focus();
                                        break;
                                    }
                            }
                            break;
                        }
                    case Keys.Up:
                        {
                            XuLyKeyUp();
                            break;
                        }
                    case Keys.Down:
                        {
                            XuLyKeyDown();
                            break;
                        }
                }
            }
            catch
            {
            }
        }

        void dgvHienThi_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            SuaHangHoa();
        }

        void dgvHienThi_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (hanhDong != Common.Constants.Insert)
                return;
            try
            {
                i = e.RowIndex;
                if (i < 0)
                    return;
                if (dgvHienThi.RowCount == 0)
                    return;
                save = ((Entities.ChiTietHDBanle[])dgvHienThi.DataSource)[i];
            }
            catch
            {
            }

        }

        void btnTimKH_Click(object sender, EventArgs e)
        {
            ThemKhachHang();
        }

        void btnTheVip_Click(object sender, EventArgs e)
        {
            TheVip();
        }

        void btnThemGV_Click(object sender, EventArgs e)
        {
            XuLy_Enter();
        }

        void btnThanhToan_Click(object sender, EventArgs e)
        {
            ThanhToan();
        }

        void txtTyLeTinh_TextChanged(object sender, EventArgs e)
        {
            TextBox temp = (TextBox)sender;
            int vt = temp.SelectionStart;
            string str = new string(temp.Text.ToList<char>().Where(c => char.IsNumber(c)).ToArray<char>());

            temp.Text = str;

            temp.SelectionStart = vt;
        }

        void btnThoat_Click(object sender, EventArgs e)
        {
            Thoat();
        }

        void frmXuLy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!checkClose)
                if (MessageBox.Show(Common.MSG.MSG2(), Common.MSG.TieuDe, MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                    e.Cancel = checkClose;
                else
                    e.Cancel = !checkClose;
            else
            {
                MyGetData(kiemtra);
            }
        }

        #region xử lý tiền tệ
        void XuLyTienTe()
        {
        }
        #endregion

        #region xử lý chính sách giá khuyến mại
        Entities.ChiTietChinhSachGiaHangHoa[] ctcsghh;
        Entities.ChiTietChinhSachGiaHangHoa[] CheckChinhSachGiaHangHoa()
        {
            try
            {
                ArrayList array = new ArrayList();
                foreach (Entities.ChinhSachGiaHangHoa item in chinhsachgiahanghoa)
                {
                    if (item.GiaTriTrangThai == "Đang sử dụng")
                    {
                        array.Add(item);
                    }
                }
                Entities.ChinhSachGiaHangHoa[] csghh = (Entities.ChinhSachGiaHangHoa[])array.ToArray(typeof(Entities.ChinhSachGiaHangHoa));

                array = new ArrayList();
                foreach (Entities.ChinhSachGiaHangHoa item in csghh)
                {
                    foreach (Entities.ChiTietChinhSachGiaHangHoa item1 in chitietchinhsachgiahanghoa)
                    {
                        if (item.MaChinhSachGiaHangHoa == item1.MaChinhSachGiaHangHoa)
                        {
                            array.Add(item1);
                        }
                    }
                }
                ctcsghh = (Entities.ChiTietChinhSachGiaHangHoa[])array.ToArray(typeof(Entities.ChiTietChinhSachGiaHangHoa));
                return ctcsghh;
            }
            catch
            {
                return new Entities.ChiTietChinhSachGiaHangHoa[0];
            }
        }

        bool ChinhSachGiaHangHoa()
        {
            try
            {
                ctcsghh = CheckChinhSachGiaHangHoa();
                if (ctcsghh.Length == 0)
                    return false;

                return true;
            }
            catch
            {
                return false;
            }
        }

        Entities.ChiTietHDBanle[] XuLyChinhSachGiaHangHoa(Entities.ChiTietHDBanle[] chitiethdbanle)
        {
            try
            {
                ArrayList array = new ArrayList();
                if (ChinhSachGiaHangHoa())
                {
                    foreach (Entities.ChiTietHDBanle item in chitiethdbanle)
                    {
                        if (item.DonGia != "0")
                        {
                            bool kt = false;
                            foreach (Entities.ChiTietChinhSachGiaHangHoa item1 in ctcsghh)
                            {
                                if (item.MaHangHoa == item1.MaHangHoa && item.SoLuong >= item1.SoLuong)
                                {
                                    item.PhanTramChietKhau = item1.PhanTramGiaBanLe;
                                    double dongiatruockhichietkhau = double.Parse(item.DonGia);
                                    double dongiasaukhichietkhau = (dongiatruockhichietkhau - (dongiatruockhichietkhau * double.Parse(item.PhanTramChietKhau)) / 100);
                                    double thanhtiensaukhichietkhau = dongiasaukhichietkhau * item.SoLuong;
                                    double thuesaukhichietkhau = (thanhtiensaukhichietkhau * double.Parse(item.ThueGTGT)) / 100;
                                    item.ThanhTien = ((thanhtiensaukhichietkhau + thuesaukhichietkhau)).ToString();
                                    array.Add(item);
                                    kt = true;
                                    break;
                                }
                            }
                            if (!kt)
                                array.Add(item);
                        }
                        else
                            array.Add(item);
                    }
                    hienthi = (Entities.ChiTietHDBanle[])array.ToArray(typeof(Entities.ChiTietHDBanle));
                    return hienthi;
                }
                else
                {
                    return chitiethdbanle;
                }
            }
            catch
            {
                return new Entities.ChiTietHDBanle[0];
            }
        }
        #endregion

        #region xử lý Khuyến mại tặng hàng
        Entities.ChiTietKhuyenMaiTangHang[] CheckKhuyenMaiTangHang()
        {
            try
            {
                ArrayList array = new ArrayList();
                foreach (Entities.KhuyenMaiTangHang item in khuyenmaitanghang)
                {
                    if (item.GiaTriTrangThai == "Đang sử dụng")
                    {
                        array.Add(item);
                    }
                }
                Entities.KhuyenMaiTangHang[] kmth = (Entities.KhuyenMaiTangHang[])array.ToArray(typeof(Entities.KhuyenMaiTangHang));

                array = new ArrayList();
                foreach (Entities.KhuyenMaiTangHang item in kmth)
                {
                    foreach (Entities.ChiTietKhuyenMaiTangHang item1 in chitietkhuyenmaitanghang)
                    {
                        if (item1.MaKhuyenMaiTangHang == item.MaKhuyenMaiTangHang)
                            array.Add(item1);
                    }
                }
                ctkmth = (Entities.ChiTietKhuyenMaiTangHang[])array.ToArray(typeof(Entities.ChiTietKhuyenMaiTangHang));
                return ctkmth;
            }
            catch
            {
                return new Entities.ChiTietKhuyenMaiTangHang[0];
            }
        }
        Entities.HangHoa[] manghanghoa;
        int tyle;
        Entities.ChiTietKhuyenMaiTangHang[] ctkmth;
        bool KhuyenMaiTangHang()
        {
            try
            {
                ctkmth = CheckKhuyenMaiTangHang();
                if (ctkmth.Length == 0)
                    return false;
                manghanghoa = CheckSuaHangHoaKhuyenMai();
                if (manghanghoa.Length != 0)
                    return true;
                return false;
            }
            catch
            {
                return false;
            }
        }

        Entities.HangHoa LayHangHoa(string mahangkhuyenmai, int soluog, bool kt)
        {
            try
            {
                List<Entities.HangHoa> hh = new List<Entities.HangHoa>();
                foreach (Entities.HangHoa item in hanghoa)
                {
                    hh.Add(item);
                }
                foreach (Entities.HangHoa item in Common.Utilities.CheckGoiHang(hanghoa, goihang, chitietgoihang))
                {
                    hh.Add(item);
                }
                foreach (Entities.HangHoa item in hh)
                {
                    if (item.MaHangHoa.ToUpper() == mahangkhuyenmai.ToUpper())
                    {
                        item.SoLuong = soluog;
                        item.KhuyenMai = kt;
                        return item;
                    }
                }
                return null;
            }
            catch
            {
                return null;
            }
        }
        #endregion

        #region Xử lý chuỗi mã hàng hóa
        bool XuLyChuoiMaHangHoa()
        {
            try
            {
                bool kt = false;
                mahanghoa = txtMaHangHoa.Text.ToUpper();
                //if (lbTenHangHoa.Text.ToString() == "")
                {
                    foreach (Entities.HangHoa item in hanghoa)
                    {
                        if (item.MaHangHoa.ToUpper() == mahanghoa.ToUpper())
                        {
                            txtMaHangHoa.Text = item.MaHangHoa.ToUpper();
                            txtTenHangHoa.Text = item.TenHangHoa;
                            thuegtgt = LayThue(item.MaThue);
                            dongia = item.GiaBanLe;
                            txtDonGia.Text = dongia;
                            kt = true;
                            break;
                        }
                    }
                    if (!kt)
                    {
                        foreach (Entities.GoiHang item in goihang)
                        {
                            if (item.MaGoiHang.ToUpper() == mahanghoa.ToUpper())
                            {
                                txtMaHangHoa.Text = item.MaGoiHang.ToUpper();
                                txtTenHangHoa.Text = item.TenGoiHang;
                                kt = true;
                                checkgoihang = true;
                                break;
                            }
                        }
                        if (!kt)
                        {
                            MessageBox.Show(Common.MSG.MSG27(mahanghoa.ToUpper()), Common.MSG.TieuDe, MessageBoxButtons.OK);
                            mahanghoa = "";
                            return false;
                        }
                    }
                }
                khuyenmai = false;
                return true;
            }
            catch
            {
                return false;
            }
        }

        void XuLy_Enter()
        {
            try
            {
                if (hanhDong != Common.Constants.Insert) return;
                {
                    if (makho.Length == 0 || makho == "NULL")
                    {
                        MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return;
                    }
                    if (ValidateDetails())
                    {
                        if (!XuLyChuoiMaHangHoa())
                        {
                            return;
                        }
                        if (!checkgoihang)
                        {
                            if (!KhuyenMaiTangHang())
                            {
                                if (txtMaHangHoa.Text.Length != 0 && txtMaHangHoa.Text != "<F4 - Tra cứu>")
                                {
                                    NewRow();
                                }
                            }
                            else
                                AddRowMang();
                        }
                        else
                        {
                            string magoihang = mahanghoa;
                            int soluonggoihang = soluong;
                            for (int k = 0; k < goihang.Length; k++)
                            foreach (Entities.ChiTietGoiHang item in chitietgoihang)
                            {
                                if (goihang[k].MaGoiHang.ToUpper() == magoihang.ToUpper())
                                {
                                    mahanghoa = goihang[k].MaGoiHang;
                                    txtMaHangHoa.Text = mahanghoa;
                                    soluong = soluonggoihang;
                                    lbTenHangHoa.Text = goihang[k].TenGoiHang;
                                    dongia = goihang[k].GiaBanLe;
                                    txtDonGia.Text = dongia;
                                    if (!KhuyenMaiTangHang())
                                    {
                                        if (txtMaHangHoa.Text.Length != 0 && txtMaHangHoa.Text != "<F4 - Tra cứu>")
                                        {
                                            NewRow();
                                        }
                                    }
                                    else
                                        AddRowMang();
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            finally
            {
                checkgoihang = false;
            }
        }

        bool XuLy_EnterMaHangHoa()
        {
            try
            {
                if (hanhDong != Common.Constants.Insert) return false;
                {
                    if (makho.Length == 0 || makho == "NULL")
                    {
                        MessageBox.Show(Common.MSG.MSG28(), Common.MSG.TieuDe, MessageBoxButtons.OK);
                        return false;
                    }
                    return XuLyChuoiMaHangHoa();
                }
            }
            catch
            {
                return false;
            }
        }
        int i = 0;
        void XuLyKeyUp()
        {
            int soluong = dgvHienThi.RowCount;

            if (soluong != 0)
            {
                if (i <= 0)
                    dgvHienThi.Rows[0].Selected = true;
                else if (i >= 0 && i < soluong)
                    dgvHienThi.Rows[i - 1].Selected = true;
            }
        }

        void XuLyKeyDown()
        {
            int soluong = dgvHienThi.RowCount;
            if (soluong != 0)
            {
                if (i < 0)
                    dgvHienThi.Rows[0].Selected = true;
                else if (i >= 0 && i < soluong - 1)
                    dgvHienThi.Rows[i + 1].Selected = true;
                else if (i == soluong - 1)
                    dgvHienThi.Rows[i].Selected = true;
            }
        }
        #endregion

        private void txtMaHangHoa_Click(object sender, EventArgs e)
        {
            txtMaHangHoa.SelectAll();
        }
        #endregion
    }
}
#endregion